<template>
  <section class="todoapp">
    <TodoHeader @addlist="addlist" />
    <TodoMain
      :todolist="Renderlist"
      @dellist="dellist"
      @changeFlag="changeFlag"
      @changeBtn="changeBtn"
    />
    <TodoFooter
      :sum="sum"
      :todolist="Renderlist"
      @thislist="delAlllist"
      @changelist="changelist"
    />
  </section>
</template>

<script>
import TodoHeader from './components/Todoheader.vue'
import TodoMain from './components/Todomain.vue'
import TodoFooter from './components/Todofooter.vue'
import { nanoid } from 'nanoid'
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('AllList')) || [
        {
          flag: false,
          value: '读万卷书',
          id: 1,
        },
        {
          flag: false,
          value: '行万里路',
          id: 2,
        },
        {
          flag: false,
          value: '书中自有黄金屋',
          id: 3,
        },
      ],

      alltype: 'All',
    }
  },
  methods: {
    addlist(add) {
      this.list = [
        {
          flag: false,
          value: add,
          id: nanoid(),
        },
        ...this.list,
      ]
    },
    dellist(id) {
      const event = this.list.find((item) => item.id === id)
      if (event.flag === false) return alert('未完成不要删除')
      this.list = this.list.filter((item) => {
        return item.id !== id
      })
    },
    changeFlag(id, checked) {
      this.list.forEach((item) => {
        if (item.id === id) item.flag === checked
      })
    },
    delAlllist(dellist) {
      this.list = dellist
    },
    changeBtn(value) {
      this.list.forEach((item) => {
        item.flag = value
      })
    },
    changelist(boxid) {
      this.alltype = boxid
    },
  },
  computed: {
    sum() {
      // return this.list.filter((item) => !item.flag).length
      return this.list.reduce((p, i) => (i.flag ? p + 0 : (p += 1)), 0)
    },
    Renderlist() {
      // switch (this.alltype) {
      //   case 'completed':
      //     return this.list.filter((item) => item.flag === true)
      //   case 'active':
      //     return this.list.filter((item) => item.flag === false)
      //   default:
      //     return this.list
      // }
      return this.alltype === 'All'
        ? this.list
        : this.alltype === 'completed'
        ? this.list.filter((item) => item.flag === true)
        : this.list.filter((item) => item.flag === false)
    },
  },
  watch: {
    list: {
      immediate: true,
      deep: true,
      handler(newValue) {
        localStorage.setItem('AllList', JSON.stringify(newValue))
      },
    },
  },
}
</script>

<style></style>
